package com.xiaolanshu.controller;

import com.xiaolanshu.entity.User;
import com.xiaolanshu.exception.BusinessException;
import com.xiaolanshu.service.LoginService;
import com.xiaolanshu.service.UserService;
import com.xiaolanshu.utils.JwtUtils;
import com.xiaolanshu.vo.ErrorResult;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private LoginService loginService;

    /**
     * 发送短信验证码接口
     *
     */
    @PostMapping("/smsLogin")
    public ResponseEntity SmsLogin(@RequestParam Map pram){

        String phone = (String)pram.get("phone");

        userService.sendMsg(phone);

        //返回短信验证码，前端测试使用
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);

        return ResponseEntity.status(200).body(redisCode);

    }

    /**
     * 普通用户登录
     * @param param
     * @return
     */
    @PostMapping("/userLogin")
    public ResponseEntity login(@RequestBody Map param){

        Map<Object, Object> re = loginService.userLogin(param);

        return ResponseEntity.ok(re);
    }

    /**
     * 管理员后台登录
     * @param param
     * @return
     */
    @PostMapping("/adminLogin")
    public ResponseEntity adminLogin(@RequestBody Map param){

        String userType = (String) param.get("userType");
        //判断是否为管理员用户
        if(!userType.equals("admin")){
            return ResponseEntity.ok("登录失败，非管理员用户");
        }

        Map<Object, Object> re = loginService.userLogin(param);

        return ResponseEntity.ok(re);
    }


    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity register(@RequestBody User user){

        //将密码加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(password);

        //保存用户信息
        userService.saveUser(user);

        return ResponseEntity.status(200).body("注册成功");
    }

    /**
     * 上传用户头像
     * @param headphoto
     * @return
     */
    @PostMapping("/headphoto")
    public ResponseEntity uploadHeadphoto(MultipartFile headphoto) throws Exception {

        String headphotoUrl = userService.uploadHeadphoto(headphoto);

        return ResponseEntity.ok(headphotoUrl);

    }
}
